package cn.edu.ecut.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.time.LocalDateTime;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet( urlPatterns = "/prepared" , loadOnStartup = 1 , name = "zouge" )
public class PreparedServlet implements Servlet {
	
	public PreparedServlet() {
		super();
		System.out.println( "Constructor : " + this );
	}
	
	private OutputStream out ;
	private OutputStreamWriter writer ;

	@Override
	public void init(ServletConfig config) throws ServletException {
		System.out.println( "servlet instance init : " + this );
		// System.out.println( config );
		System.out.println( "servlet name : " + config.getServletName() );
		try{
			out = new FileOutputStream( "D:/prepared.txt" );
			writer = new OutputStreamWriter( out );
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void service( ServletRequest req , ServletResponse resp ) throws ServletException, IOException {
		// 向 控制台 输出信息
		System.out.println( "Servlet实例( " + this + " )正在提供服务 " );
		
		// 使用在 init 方法中创建的字符流输出数据到文件
		writer.write( LocalDateTime.now().toString() );
		
		resp.setContentType( "text/html;charset=UTF-8" );
		PrintWriter out = resp.getWriter();
		out.println( "<div style='text-align:center;font-size:20px;'>" + LocalDateTime.now() + "</div>" );
	}

	@Override
	public void destroy() {
		System.out.println( "容器释放Servlet实例所占用的资源 : " + this );
		try {
			writer.close();
			out.close();
		} catch( IOException e ) {
			e.printStackTrace();
		}
	}

	@Override
	public ServletConfig getServletConfig() {
		return null;
	}

	@Override
	public String getServletInfo() {
		return null;
	}
}
